package org.zn.etl.config;

import java.util.Arrays;

import javax.sql.DataSource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan(basePackages = {"org.zn.etl.job.dao","org.zn.quality.dao"}, sqlSessionFactoryRef = "etlSqlSessionFactory")
@Configuration
@EnableTransactionManagement
public class MybatisConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.etldatasource")
    DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "transactionManager")
	 PlatformTransactionManager transactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}

	@Bean
	SqlSessionFactory etlSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		
		DataSource etlbase =dataSource();
		
		sessionFactoryBean.setDataSource(etlbase);
		String locationPattern = "classpath*:/mapper/etl/*.xml";
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		
		Resource[] base=resolver.getResources(locationPattern);
		//Resource[] extUser=resolver.getResources("classpath*:/mapper/extuser/*.xml");
		//Resource[] all=ArrayUtils.addAll(base, extUser);
		
		sessionFactoryBean.setMapperLocations(base);
		return sessionFactoryBean.getObject();
	}

	@Bean(name = "EtlSqlSessionTemplate")
	SqlSessionTemplate sqlSessionTemplate1(
			@Qualifier("etlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
